package evi.com.evi.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import evi.com.evi.R;
import evi.com.evi.adapter.GoodsInfoAdapter;
import evi.com.evi.adapter.ListSortAdapter;
import evi.com.evi.application.MyApplication;
import evi.com.evi.bean.ClassifyBean;
import evi.com.evi.bean.GoodsManagerBean;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 商品管理
 *
 * @author MY
 */
public class GoodsManagerActivity extends Activity implements OnClickListener {
    private static final String TAG = "TAG";

    private ImageView tv_return_back;

    private TextView tv_add_goods;

    private View footerView;
    private TextView tv_sort_add;
    private TextView tv_sort_write;

    private ListView lv_goods_sort;
    private ListSortAdapter mListSortAdapter;

    private ListView lv_goods_info;
    private GoodsInfoAdapter mGoodsInfoAdapter;

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    private List<ClassifyBean> sortList; //分类List
    private List goodList; //商品List

    public GoodsManagerBean bean;
    public int mPosition = 0;       //当前选择的分类

    private boolean isAddFooter = false;        //是否添加过listview的footer

    private Dialog dialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranStatus(this, false, Color.parseColor("#FF6600"));
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_goods_manager);
        initView();
    }

    private void initView() {
        tv_return_back = (ImageView) findViewById(R.id.tv_return_back);
        tv_return_back.setOnClickListener(this);

        tv_add_goods = (TextView) findViewById(R.id.tv_add_goods);
        tv_add_goods.setOnClickListener(this);

        footerView = LayoutInflater.from(this).inflate(R.layout.view_sort_add, null);
        tv_sort_add = (TextView) footerView.findViewById(R.id.tv_sort_add);
        tv_sort_write = (TextView) footerView.findViewById(R.id.tv_sort_write);
        tv_sort_add.setOnClickListener(this);
        tv_sort_write.setOnClickListener(this);

        lv_goods_sort = (ListView) findViewById(R.id.lv_goods_sort);
        lv_goods_info = (ListView) findViewById(R.id.lv_goods_info);

        client = new OkHttpClient();
        jsonUtils = new JSONUtils();

        sortList = new ArrayList();
        goodList = new ArrayList();

        lv_goods_sort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //执行查询操作...
                mPosition = position;
                mListSortAdapter.dataIndex = position;
                mListSortAdapter.notifyDataSetChanged();
                showInfo();
            }
        });


        getGoodsInfo();
    }

    //分类
    private void showSort() {
        Comparator<ClassifyBean> comparator = new Comparator<ClassifyBean>() {
            @Override
            public int compare(ClassifyBean o1, ClassifyBean o2) {
                return o1.getSort().compareTo(o2.getSort());
            }
        };
        Collections.sort(sortList, comparator);

        mListSortAdapter = new ListSortAdapter(GoodsManagerActivity.this, sortList);
        lv_goods_sort.setAdapter(mListSortAdapter);
        if (!isAddFooter) {
            isAddFooter = true;
            mPosition = 0;
            lv_goods_sort.addFooterView(footerView);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_return_back:
                finish();
                break;

            case R.id.tv_add_goods:     //添加商品
                Intent intent1 = new Intent(GoodsManagerActivity.this, GoodsAddActivity.class);
                intent1.putExtra("ActType", "添加商品");
                startActivityForResult(intent1, 1);
                break;

            case R.id.tv_sort_add:      //添加分类
                Intent intent2 = new Intent(GoodsManagerActivity.this, GoodsUpdateActivity.class);
                intent2.putExtra("ActType", "添加分类");
                startActivityForResult(intent2, 1);
                break;

            case R.id.tv_sort_write:    //编辑分类
                Intent intent3 = new Intent(GoodsManagerActivity.this, GoodsSortWriteActivity.class);
                intent3.putExtra("jsonData", bean);
                startActivityForResult(intent3, 1);
                break;
            default:
                break;
        }
    }

    //返回回调方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "resultCode: " + resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                sortList = new ArrayList<>();
                mPosition = 0;
                getGoodsInfo();
            }
        } else if(resultCode == RESULT_CANCELED){
            sortList = new ArrayList<>();
            mPosition = 0;
            getGoodsInfo();
        }
    }

    //商品
    private void showInfo() {
        List<GoodsManagerBean.DataBean.CategoriesBean.ProductsBean> products = new ArrayList<>();
        List<GoodsManagerBean.DataBean.CategoriesBean> categories = bean.getData().getCategories();
        String name = null;
        String category = null;
        for (GoodsManagerBean.DataBean.CategoriesBean info : categories) {

            String a = info.getProductCategoryId();
            String b = sortList.get(mPosition).getProductCategoryId();
            Log.e(TAG, "mPosition" + mPosition);
            if (a.equals(b)) {
                products.addAll(info.getProducts());
                name = info.getName();
                category = info.getProductCategoryId();
            }
        }
        mGoodsInfoAdapter = new GoodsInfoAdapter(GoodsManagerActivity.this, products, name, category);
//        mGoodsInfoAdapter = new GoodsInfoAdapter(GoodsManagerActivity.this, products, name, category);
        lv_goods_info.setAdapter(mGoodsInfoAdapter);
    }

//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        getGoodsInfo();
//    }

    private void getGoodsInfo() {
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在连接服务器，请稍等");
        dialog.show();
        sortList.clear();
        String token = SPUtil.getString(this, "token");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.merchantCategoryProducts_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器忙碌，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    bean = JSON.parseObject(jsonData, GoodsManagerBean.class);
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("categories");
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject sort = jsonArray.getJSONObject(i);
                            sortList.add(new ClassifyBean(sort.getString("productCategoryId"), sort.getString("name"), sort.getString("sorter")));
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSort();
                                showInfo();
                                mListSortAdapter.notifyDataSetChanged();
                                mGoodsInfoAdapter.notifyDataSetChanged();
                                dialog.dismiss();
                            }
                        });
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }

                Log.e(TAG, "商品信息联网成功" + jsonData);
            }
        });

    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(GoodsManagerActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }
}